<template>
    <el-card shadow="never">
        <template #header>
            <div class="flex justify-between">
                <span class="text-sm">订单统计</span>
                <div>
                    <el-check-tag v-for="(item, index) in options" :key="index" :checked="current === item.value"
                        style="margin-right:8px" @click="handleChoose(item.value)">{{ item.text }}</el-check-tag>
                </div>
            </div>
        </template>
        <div ref="el" id="chart" style="width: 100%;height: 300px;"></div>
    </el-card>

</template>

<script setup>
import {
    ref,
    onMounted,
    onBeforeUnmount
} from 'vue';
import * as echarts from 'echarts';
// 修正拼写错误
import { useResizeObserver } from '@vueuse/core';
import {
    getStatistics3
} from "~/api/index.js";

const current = ref("week");
const options = [
    {
        text: "近一个月",
        value: "month"
    },
    {
        text: "近一周",
        value: "week"
    },
    {
        text: "近24小时",
        value: "hour"
    }
];

const handleChoose = (type) => {
    current.value = type;
    // 当选择项改变时，重新获取数据并更新图表
    getData();
};

let myChart = null;
onMounted(() => {
    const chartDom = document.getElementById('chart');
   if(chartDom){
    myChart = echarts.init(chartDom);
    getData()
   }
});

onBeforeUnmount(() => {
    // 修正 echarts.dispose 调用
    if (myChart) echarts.dispose(myChart);
})

function getData() {
    const option = {
        xAxis: {
            type: 'category',
            data: [],
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data: [],
                type: 'bar',
                showBackground: true,
                backgroundStyle: {
                    color: 'rgba(180, 180, 180, 0.2)'
                }
            }
        ]
    };

    getStatistics3(current.value)
      .then(res => {
            // 检查数据类型，确保是数组
            if (Array.isArray(res.x) && Array.isArray(res.y)) {
                option.xAxis.data = res.x;
                option.series[0].data = res.y;
                myChart.setOption(option);
            } else {
                console.error('数据格式不正确，x或y不是数组');
                // 这里可以添加toast提示用户数据格式错误
            }
        })
      .catch(error => {
            console.error('数据获取失败:', error);
            // 这里可以添加toast提示用户数据获取失败
        });
}

const el = ref(null)
useResizeObserver(el, (entries) => myChart.resize())
</script>

<style>
</style>  